package com.summer.study.leetcode.thread.chain;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @auther: 杨杰
 * @date: 2019/7/25 15:17
 * @description:
 */
public class Leader {

    private ReentrantLock lock;

    private int num=10;

    private Condition thisCondition;

    private Condition nextCondition;

    private char c;

    public Leader(ReentrantLock lock,char c, Condition thisCondition, Condition nextCondition) {
        this.lock=lock;
        this.c = c;
        this.thisCondition = thisCondition;
        this.nextCondition = nextCondition;
    }


    public void print(){
        lock.lock();
        try {
            for(int i=0;i<num;i++){
                System.out.println(c);
                nextCondition.signal();
            }
        }finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        ReentrantLock lock = new ReentrantLock();
        // 打印a线程的condition
        Condition conditionA = lock.newCondition();
        // 打印b线程的condition
        Condition conditionB = lock.newCondition();
        // 打印c线程的condition
        Condition conditionC = lock.newCondition();

        Leader first=new Leader(lock,'A',conditionA,conditionB);

        Leader second=new Leader(lock,'B',conditionB,conditionC);

        Leader third=new Leader(lock,'C',conditionC,conditionA);

        new Thread(() -> {
            first.print();
        }).start();
        new Thread(() -> {
            second.print();
        }).start();
        new Thread(() -> {
            third.print();
        }).start();
    }

}
